'use strict';
const cp = require('child_process');
const path = require('path');
const log = require('@dpx-cli-dev/log');
const Package = require('@dpx-cli-dev/package');
const SETTINGS = {
  init: '@dpx-cli-dev/init',
};
const CACHE_DIR = 'dependencies';
async function exec() {
  let targetPath = process.env.CLI_TARGET_PATH;
  let storeDir = '';
  let pkg;
  const homePath = process.env.CLI_HOME_PATH;
  const cmdObj = arguments[arguments.length - 1];
  const cmdName = cmdObj.name();
  const packageName = SETTINGS[cmdName]; // SETTINGS[cmdName]; axios
  const packageVersion = 'latest'; // 'latest';
  if (!targetPath) {
    targetPath = path.resolve(homePath, CACHE_DIR);
    storeDir = path.resolve(targetPath, 'node_modules');
    log.verbose('targetPath', targetPath);
    log.verbose('storeDir', storeDir);
    pkg = new Package({
      targetPath,
      storeDir,
      packageName,
      packageVersion,
    });
    if (await pkg.exists()) {
      // 更新
      console.log('enter update');
      await pkg.update();
    } else {
      // 安装
      await pkg.install();
    }
  } else {
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion,
    });
  }
  const rootFile = pkg.getRootFilePath();
  // console.log(rootFile, 'rootFile');
  if (rootFile) {
    try {
      // require(rootFile).call(null, Array.from(arguments));
      // 在node子进程中调用
      const args = Array.from(arguments);
      const cmd = args[args.length - 1];
      const o = Object.create(null);
      Object.keys(cmd).forEach((key) => {
        if (
          cmd.hasOwnProperty(key) &&
          !key.startsWith('_') &&
          key !== 'parent'
        ) {
          o[key] = cmd[key];
        }
      });
      args[args.length - 1] = o;
      // console.log(args, 'dmd');
      const code = `require("${rootFile}").call(${null}, ${JSON.stringify(
        args
      )});`;
      // const child = cp.spawn('cmd', ['/c', 'node', '-e', code], {
      //   cwd: process.cwd()
      // });
      // const code = 'console.log(11);';
      const child = spawn('node', ['-e', code], {
        cwd: process.cwd(),
        // shell: true,
        stdio: 'inherit',
      });
      child.on('error', (e) => {
        log.error(e.message);
        process.exit(1);
      });
      child.on('exit', (e) => {
        log.verbose('命令执行成功：' + e);
        process.exit(e);
      });
      // child.stdout.on('data', (chunk) => {});
      // child.stderr.on('data', (chunk) => {});
    } catch (e) {
      log.error(e.message);
    }
  }
}
function spawn(command, args, options) {
  const win32 = process.platform === 'win32';
  const cmd = win32 ? 'cmd' : command;
  const cmdArgs = win32 ? ['/c'].concat(command, args) : args;
  return cp.spawn(cmd, cmdArgs, options || {});
}

module.exports = exec;
